package com.company.card_service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.company.card_service.mapper.CompanyModelMapper;
import com.company.card_service.mapper.UserInfoMapper;
import com.company.card_service.mapper.UserMapper;
import com.company.card_service.model.CompanyCaseType;
import com.company.card_service.model.CompanyModel;
import com.company.card_service.model.CompanyProfileType;
import com.company.card_service.mapper.CompanyProfileTypeMapper;
import com.company.card_service.model.User;
import com.company.card_service.service.CompanyProfileTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.card_service.util.PageHelper;
import com.company.card_service.vo.CompanyProfileTypeVo;
import com.company.card_service.vo.Result;
import com.company.card_service.vo.ResultCodeEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.nio.file.Watchable;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 赵志浩
 * @since 2022-09-15 04:15:06
 */
@Service
public class CompanyProfileTypeServiceImpl extends ServiceImpl<CompanyProfileTypeMapper, CompanyProfileType> implements CompanyProfileTypeService {
    @Autowired
    private CompanyProfileTypeMapper companyProfileTypeMapper;
    @Autowired
    private CompanyProfileType companyProfileType;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CompanyModelMapper companyModelMapper;
    @Override
    public Result selectCompanyProfileType(int cid) {
//        QueryWrapper<CompanyProfileType> wrapper = new QueryWrapper<CompanyProfileType>()
//                .eq("is_deleted",0)
//                .orderByAsc("id");
//        List<CompanyProfileType> companyProfileTypes = companyProfileTypeMapper.selectList(wrapper);
        List<CompanyProfileTypeVo> companyProfileTypeVos = companyProfileTypeMapper.selectCompanyProfileTypeListById(cid);
        if (companyProfileTypeVos.size() == 0){
            return Result.fail(ResultCodeEnum.FAIL.getCode(),ResultCodeEnum.FAIL.getMessage());
        }else {
            return Result.success(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage(),companyProfileTypeVos);
        }
    }

    @Override
    public Result selectCompanyProfileTypePageById(int cid, int pageNum, int limit) {

        //1.根据公司id查询总分类
        List<CompanyProfileTypeVo> companyProfileTypeVos = companyProfileTypeMapper.selectCompanyProfileTypeListById(cid);//统计总分类数
        //1.1.根据管理员id查找名字
        int count = companyProfileTypeVos.size();
        //2.计算总页数（必须确定每页显示多少条  pageSize = limit）
        int pageCount = count%limit==0?count/limit:count/limit +1;
        //3.查询当前页的数据
        int start = (pageNum-1)*limit;
        List<CompanyProfileTypeVo> vos = companyProfileTypeMapper.selectCompanyProfileTypePageById(cid, start, limit);

        vos = vos.stream().sorted((Comparator.comparing(CompanyProfileType::getSort))).collect(Collectors.toList());
        return Result.success(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage(),new PageHelper<CompanyProfileTypeVo>(count,pageCount,vos));
    }

    @Override
    public Result addCompanyProfileType(CompanyProfileType cptv) {
        //通过前端传过来的管理员ID查找管理员信息
        User user = userMapper.selectById(cptv.getSysUserId());
       Long cptvid =  user.getId();
        cptv.setCreateTime(new Date());
        cptv.setSysUserId(Math.toIntExact(cptvid));


        int i = companyProfileTypeMapper.insert(cptv);
        if (i > 0){
            return Result.success(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage(),i);
        }else {
            return Result.fail(ResultCodeEnum.FAIL.getCode(),ResultCodeEnum.FAIL.getMessage());
        }
    }

    @Override
    public Result updateCompanyProfileType(CompanyProfileType cpt) {
//        QueryWrapper<CompanyProfileType> wrapper = new QueryWrapper<>();
//        wrapper.eq("company_id",cid);
//        int i = companyProfileTypeMapper.update(cpv, wrapper);
        cpt.setUpdateTime(new Date());
        int i = companyProfileTypeMapper.updateById(cpt);
        if (i > 0){
            return Result.success(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage(),i);
        }else {
            return Result.fail(ResultCodeEnum.FAIL.getCode(),ResultCodeEnum.FAIL.getMessage());
        }
    }

    @Override
    public Result deleteCompanyProfileTypeById(int id) {
        UpdateWrapper<CompanyProfileType> wrapper = new UpdateWrapper<>();
        wrapper.eq("id",id);
        wrapper.set("is_deleted",1);
        int i = companyProfileTypeMapper.update(companyProfileType, wrapper);
        if (i > 0){
            return Result.success(ResultCodeEnum.SUCCESS.getCode(),ResultCodeEnum.SUCCESS.getMessage(),i);
        }else {
            return Result.fail(ResultCodeEnum.FAIL.getCode(),ResultCodeEnum.FAIL.getMessage());
        }
    }


    /**
     * 下移
     * @param sysUserId
     * @param modelId
     * @param caseTypeId
     */
    @Transactional
    public void findNext(Integer sysUserId, Integer modelId, Integer caseTypeId) {
        //查询当前公司 对应模块的分类
        List<CompanyProfileType> next = companyProfileTypeMapper.findNext(sysUserId, modelId);
        //根据sort排序
        List<CompanyProfileType> collect = next.stream().sorted(Comparator.comparing(CompanyProfileType::getSort)).collect(Collectors.toList());
        //下移
        this.selectNext(collect,caseTypeId);
    }

    /**
     * 下移的方法
     * @param collect
     * @param caseTypeId
     */
    private void selectNext(List<CompanyProfileType> collect, Integer caseTypeId) {
        //记录下标
        int xia = 0;
        //根据caseTypeId再集合中找到 当前caseTypeId 的下标 并记录
        for (int i = 0; i < collect.size(); i++) {
            if(collect.get(i).getId().equals(caseTypeId)){
                xia = i;
            }
        }
        //根据记录的下标 找到对应的CompanyCaseType
        if(collect.size() > 2){
            CompanyProfileType currentEl = collect.get(xia);
            //记录的下标加一 就是下一个元素的下标 ，然后找到 下一个下标对应的CompanyCaseType
            CompanyProfileType nextEl = collect.get(xia + 1);
            //分别获取 他们的sort
            Integer currentElCompanyId = currentEl.getSort();
            Integer nextElCompanyId = nextEl.getSort();
            //交换他们的sort
            nextEl.setSort(currentElCompanyId);
            currentEl.setSort(nextElCompanyId);
            //修改数据
            companyProfileTypeMapper.updateById(currentEl);
            companyProfileTypeMapper.updateById(nextEl);
        }
    }


    /**
     * 上移
     * @param sysUserId
     * @param modelId
     * @param caseTypeId
     */
    @Override
    public void findPre(Integer sysUserId, Integer modelId, Integer caseTypeId) {
        //查询当前公司 对应模块的分类
        List<CompanyProfileType> next = companyProfileTypeMapper.findPre(sysUserId, modelId);
        //根据sort排序
        List<CompanyProfileType> collect = next.stream().sorted(Comparator.comparing(CompanyProfileType::getSort)).collect(Collectors.toList());
        //上移
        this.selectPre(collect,caseTypeId);
    }


    @Override
    public void addCaseType(CompanyProfileType companyProfileType) {
        LambdaQueryWrapper<CompanyProfileType> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CompanyProfileType::getCompanyId,companyProfileType.getCompanyId());
        wrapper.eq(CompanyProfileType::getModelId,companyProfileType.getModelId());
        List<CompanyProfileType> companyProfileTypes = baseMapper.selectList(wrapper);
        Optional<CompanyProfileType> max = companyProfileTypes.stream().max(Comparator.comparing(CompanyProfileType::getSort));
        CompanyProfileType caseType = max.get();
        Integer maxSort = caseType.getSort();
        companyProfileType.setSort(maxSort+1);
        baseMapper.insert(companyProfileType);
    }

    /**
     * 上移的方法
     * @param collect
     * @param caseTypeId
     */

    private void selectPre(List<CompanyProfileType> collect, Integer caseTypeId) {
        //记录下标
        int xia = 0;
        //根据caseTypeId再集合中找到 当前caseTypeId 的下标 并记录
        for (int i = 0; i < collect.size(); i++) {
            if(collect.get(i).getId().equals(caseTypeId)){
                xia = i;
            }
        }
        //根据记录的下标 找到对应的CompanyCaseType
        CompanyProfileType currentEl = collect.get(xia);
        //记录的下标减一 就是上一个元素的下标 ，然后找到 上一个下标对应的CompanyCaseType
        CompanyProfileType nextEl = collect.get(xia - 1);
        //分别获取 他们的sort
        Integer currentElCompanyId = currentEl.getSort();
        Integer nextElCompanyId = nextEl.getSort();
        //交换他们的sort
        nextEl.setSort(currentElCompanyId);
        currentEl.setSort(nextElCompanyId);
        //修改数据
        companyProfileTypeMapper.updateById(currentEl);
        companyProfileTypeMapper.updateById(nextEl);
    }

}
